<template>
    <div>
     <el-form
     class="studentBox"
    ref="studentFormRef"
    :model="updateStudent"
    :rules="rules"
    label-width="100px"
    label-position="rigth">
    <el-form-item label="学生姓名" prop="name">
      <el-input v-model="updateStudent.name" />
    </el-form-item>
    <el-form-item label="性别" prop="gender">
      <el-select v-model="updateStudent.gender" placeholder="请选择性别">
        <el-option v-for="item in genderOptions" :label="item.name" :value="item._id" :key="item._id" />
      </el-select>
    </el-form-item>
    <el-form-item label="所在学校" prop="school">
      <el-autocomplete
        v-model="updateStudent.school"
        :fetch-suggestions="querySearchSchool"
        clearable
        class="w-50"
        placeholder="请输入所在学校"/>
    </el-form-item>
    <el-form-item label="学生专业" prop="major">
      <el-autocomplete
        v-model="updateStudent.major"
        :fetch-suggestions="querySearchMajor"
        clearable
        class="w-50"
        placeholder="请输入学习专业"/>
    </el-form-item>
    <el-form-item label="学生年级" prop="grade">
      <el-select v-model="updateStudent.grade" placeholder="请选择年级">
        <el-option v-for="item in gradeOptions" :label="item.name" :value="item._id" :key="item._id" />
      </el-select>
    </el-form-item>
    <el-form-item label="学生学历" prop="education">
      <el-select v-model="updateStudent.education" placeholder="请选择学历">
        <el-option v-for="item in educationOptions" :label="item.name" :value="item._id" :key="item._id" />
      </el-select>
    </el-form-item>
    <el-form-item label="学习方向" prop="direction">
      <el-select v-model="updateStudent.direction" placeholder="请选择学习方向">
        <el-option v-for="item in directionOptions" :label="item.name" :value="item._id" :key="item._id" />
      </el-select>
    </el-form-item>
    <el-form-item label="身份证号码" prop="id_number">
      <el-input v-model="updateStudent.id_number" />
    </el-form-item>
    <el-form-item label="电话号码" prop="phone">
      <el-input v-model="updateStudent.phone" />
    </el-form-item>
    <el-form-item label="家长姓名" prop="parent">
      <el-input v-model="updateStudent.parent" />
    </el-form-item>
    <el-form-item label="家长电话" prop="parent_phone">
      <el-input v-model="updateStudent.parent_phone" />
    </el-form-item>
    <el-form-item label="家庭住址" prop="address">
      <el-input v-model="updateStudent.address" />
    </el-form-item>
    <el-form-item label="QQ号码" prop="qq">
      <el-input v-model="updateStudent.qq" />
    </el-form-item>
    <el-form-item label="所在班级" prop="class">
      <el-select v-model="updateStudent.class" placeholder="请选择班级">
        <el-option v-for="item in classOptions" :label="item.classname" :value="item._id" :key="item._id" />
      </el-select>
    </el-form-item>
    <el-form-item label="入学时间" prop="admission_date">
      <el-date-picker
        v-model="updateStudent.admission_date"
        type="date"
        placeholder="请选择入学时间"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <el-form-item label="授课教师" prop="teacher_id">
      <el-select v-model="updateStudent.teacher_id" placeholder="请选择授课教师">
        <el-option v-for="item in teacherOptions" :label="item.name" :value="item._id" :key="item._id" />
      </el-select>
    </el-form-item>
    <el-form-item label="班级学管" prop="manager_id">
      <el-select v-model="updateStudent.manager_id" placeholder="请选择学管">
        <el-option v-for="item in managerOptions" :label="item.name" :value="item._id" :key="item._id" />
      </el-select>
    </el-form-item>
    <el-form-item label="照片" prop="pictures">
      <el-upload :action="baseApi+'/manage/img/upload'" list-type="picture-card" :auto-upload="true" name="image" accept="image/*" :file-list="fileList" :on-change="handleChange">
    <el-icon><Plus /></el-icon>

    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)">
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)">
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
    </el-form-item>
    <el-form-item label="备注信息" prop="note">
      <Editor v-model="updateStudent.note" :api-key="tiny.apiKey" :init="tiny.init"></Editor>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="updateStudent._id == null? addData(studentFormRef):updateData(studentFormRef)">
        确定
      </el-button>
    </el-form-item>
  </el-form>
    </div>
</template>
<script setup lang="ts">
import type { classInfoData } from '@/api/class/type';
import type { majorInfoData } from '@/api/major/type';
import type { roleInfoData } from '@/api/role/type';
import type { schoolInfoData } from '@/api/school/type';
import type { studentInfoData } from '@/api/student/type';
import type { userInfoData } from '@/api/user/type';
import useClassStore from '@/store/modules/class';
import useMajorStore from '@/store/modules/major';
import useRoleStore from '@/store/modules/role';
import useSchoolStore from '@/store/modules/school';
import useUserStore from '@/store/modules/user';
import type { FormInstance, FormRules, UploadFile, UploadProps } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';

// 使用路由
const $router = useRouter()
const $route = useRoute()
// 引入学员小仓库
const studentStore = useStudentStore()
// 表单ref对象
const studentFormRef = ref();
// 表单数据收集对象
const updateStudent = ref<studentInfoData>({
    _id: null,
    name: "", // 姓名
    gender: "", // 性别
    school: "", // 学校
    major: "", // 专业
    grade: "", // 年级
    education: "", // 学历
    direction: "", // 学习方向
    id_number: "", // 身份号码
    phone: "", // 电话号码
    parent: "", // 家长姓名
    parent_phone: "", // 家长联系电话
    address: "", // 家庭住址
    qq: "", // QQ号码
    class: "", // 所在班级
    admission_date: "", // 入学时间
    teacher_id: "", // 教师id
    manager_id: "", // 学管id
    // @ts-ignore
    pictures: "", // 照片数组
    note: "", // 备注信息
})
// 自定义手机号码校验规则
const validatePhone = (_rule:any,value:any,callback:any)=>{
    value = value.trim()
    const phoneReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (value === ""){
      callback(new Error("请输入手机号码"))
    }else if(!phoneReg.test(value)){
      callback(new Error("请输入正确的手机号码"))
    }else{
      callback()
    }
}
// 自定义身份证号码校验规则
const validateIdNumber = (_rule:any,value:any,callback:any)=>{
  console.log('value',value);
  
    value = value.trim()
    const _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    const _IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
    if (value === ""){
      callback(new Error("请输入身份证号码"))
    }else if(_IDRe18.test(value) || _IDre15.test(value)){
      callback()
    }else{
      callback(new Error("请输入正确的身份证号码"))
    }
}
// 校验规则
const rules = reactive<FormRules>({
  name:[{required:true,message:"请输入姓名",trigger:'blur'}],
  gender:[{required:true,message:"请选择性别",trigger:'blur'}],
  direction:[{required:true,message:"请选择学习方向",trigger:'blur'}],
  id_number:[{required:true,trigger:'blur',validator: validateIdNumber}],
  phone:[{required:true,trigger:'blur',validator: validatePhone}],
  class:[{required:true,message:"请选择班级",trigger:'blur'}],
  admission:[{required:true,message:"请选择入学时间",trigger:'blur'}],
  teacher_id:[{required:true,message:"请选择授课教师",trigger:'blur'}],
  manager_id:[{required:true,message:"请选择班级学管",trigger:'blur'}],
})
const addData = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      updateStudent.value.pictures = getImgs()
      studentStore.addStudent((updateStudent.value as studentInfoData)).then(()=>{
        $router.replace("/student")
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const updateData = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      updateStudent.value.pictures = getImgs()
      studentStore.updateStudent(updateStudent.value).then(()=>{
        $router.replace('/student')
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}


/* ----------------富文本相关内容------------------------- */
import Editor from "@tinymce/tinymce-vue";
const tiny = reactive({
    apiKey: "w8593t1vo6t8c9rf9zdr5m40p28g9j790kfdk0lema1vq658",
    init: {
        toolbar_mode: 'sliding',
        plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount checklist mediaembed casechange export formatpainter pageembed linkchecker a11ychecker tinymcespellchecker permanentpen powerpaste advtable advcode editimage advtemplate ai mentions tinycomments tableofcontents footnotes mergetags autocorrect typography inlinecss',
        toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table mergetags | addcomment showcomments | spellcheckdialog a11ycheck typography | align lineheight | checklist numlist bullist indent outdent | emoticons charmap | removeformat',
        tinycomments_mode: 'embedded',
        tinycomments_author: 'Author name',
        mergetags_list: [
          { value: 'First.Name', title: 'First Name' },
          { value: 'Email', title: 'Email' },
        ],
        ai_request: (_request:any, respondWith:any) => respondWith.string(() => Promise.reject("See docs to implement AI Assistant")),
    },
});

// 格式化数据开始-----------------------------------------------
const classStore = useClassStore();
const roleStore = useRoleStore();
const userStore = useUserStore();
const schoolStore = useSchoolStore()
const majorStore = useMajorStore()
// 角色数组
const roleOptions = ref<roleInfoData[]>([]);
// 用户数组
const userOptions = ref<userInfoData[]>([]);
// 班级列表
const classOptions = ref<classInfoData[]>([])
// 教师id
const teacher_role_id = ref("");
// 学管id
const manager_role_id = ref("");
// 教师数组
const teacherOptions = ref<userInfoData[]>([]);
// 学管数组
const managerOptions = ref<userInfoData[]>([]);
// 学校数组
const schoolOptions = ref<schoolInfoData[]>([])
// 专业数组
const majorOptions = ref<majorInfoData[]>([])
// 性别/年级/学历/学习方向 数据类型
interface filterData{
    _id:string,
    name:string
}
// 性别数据列表
const genderOptions = ref<filterData[]>([
    {_id:"0",name:"男"},
    {_id:"1",name:"女"}
])
// 年级数据列表
const gradeOptions = ref<filterData[]>([
    {_id:"1",name:"大一"},
    {_id:"2",name:"大二"},
    {_id:"3",name:"大三"},
    {_id:"4",name:"大四"},
    {_id:"5",name:"研究生"},
])
// 学历数据列表
const educationOptions = ref<filterData[]>([
    {_id:"1",name:"专科"},
    {_id:"2",name:"本科"},
    {_id:"3",name:"硕士"},
    {_id:"4",name:"社会"},
])
// 学习方向数据列表
const directionOptions = ref<filterData[]>([
    {_id:'1',name:"web前端"},
    {_id:'2',name:"Java"},
    {_id:'3',name:"C/C++"},
    {_id:'4',name:"直播电商"},
    {_id:'5',name:"少儿编程"},
    {_id:'6',name:"嵌入式"},
])

// 获取班级列表
const getClassList = () => {
    return new Promise((resolve,_reject)=>{
        if(classStore.classes && classStore.classes.length){
        classOptions.value = classStore.classes;
        resolve(true)
        }else{
            classStore.getClassAll().then(()=>{
                classOptions.value = classStore.classes as classInfoData[];
                resolve(true)
            })
        }
    })
}
// 获取学校列表
const getSchoolList = () => {
    return new Promise((resolve,_reject)=>{
        if(schoolStore.schools && schoolStore.schools.length){
        schoolOptions.value = schoolStore.schools;
        resolve(true)
        }else{
            schoolStore.getSchoolAll().then(()=>{
                schoolOptions.value = schoolStore.schools as schoolInfoData[];
                resolve(true)
            })
        }
    })
}
// 获取专业列表
const getMajorList = () => {
    return new Promise((resolve,_reject)=>{
        if(majorStore.majors && majorStore.majors.length){
        majorOptions.value = majorStore.majors;
        resolve(true)
        }else{
            majorStore.getMajorAll().then(()=>{
                majorOptions.value = majorStore.majors as majorInfoData[];
                resolve(true)
            })
        }
    })
}
// 获取角色数组
const getRoleList = () => {
  return new Promise((resolve,_reject)=>{
    if(roleStore.roles && roleStore.roles.length){
      roleOptions.value = roleStore.roles;
      roleOptions.value.forEach((item)=>{
        if(item.name == "教师"){
          teacher_role_id.value = item._id as string
        }else if(item.name == "学管"){
          manager_role_id.value = item._id as string
        }
      });
      resolve(true)
    }else{
      roleStore.getRoleList().then(()=>{
        roleOptions.value = roleStore.roles;
      roleOptions.value.forEach((item)=>{
        if(item.name == "教师"){
          teacher_role_id.value = item._id as string
        }else if(item.name == "学管"){
          manager_role_id.value = item._id as string
        }
      });
    });
    resolve(true);
  }
});
};
// 获取用户数组
const getUserList = () => {
  return new Promise((resolve,_reject)=>{
    if(userStore.users && userStore.users.length){
      userOptions.value = userStore.users;
      userOptions.value.forEach((item)=>{
        if(item.role_id == teacher_role_id.value){
          teacherOptions.value.push(item)
        }else if(item.role_id == manager_role_id.value){
          managerOptions.value.push(item)
        }
      });
      resolve(true)
    }else{
      userStore.getUserAll().then(()=>{
        userOptions.value = userStore.users;
        userOptions.value.forEach((item)=>{
        if(item.role_id == teacher_role_id.value){
          teacherOptions.value.push(item)
        }else if(item.role_id == manager_role_id.value){
          managerOptions.value.push(item)
        }
      });
    });
    resolve(true)
  }
});
};

const querySearchSchool = (queryString: string, cb: any) => {
    // @ts-ignore
    schoolOptions.value.forEach(item=>item.value = item.schoolname)
  const results = queryString
    ? schoolOptions.value.filter(createFilter(queryString))
    : schoolOptions.value
  // call callback function to return suggestions
  cb(results)
}
const querySearchMajor = (queryString: string, cb: any) => {
    // @ts-ignore
    majorOptions.value.forEach(item=>item.value = item.majorname)
  const results = queryString
    ? majorOptions.value.filter(createFilter(queryString))
    : majorOptions.value
  // call callback function to return suggestions
  cb(results)
}
const createFilter = (queryString: string) => {
  return (restaurant: any) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}

// 关于图片上传
// 请求标识
// const baseUrl = import.meta.env.VITE_APP_SERVICE_URL
const baseApi = import.meta.env.VITE_APP_BASE_API

const handleChange: UploadProps["onChange"] = (uploadFile,uploadFiles)=>{
    // 本地上传完成
    if(uploadFile.status == "success"){
        // 后端服务器响应的内容
        const result = uploadFile.response 
        // 是否上传到服务器
        //@ts-ignore
        if(result.status == 0){
            // 取出服务器响应的图片名称和url地址
            // @ts-ignore
            const { name, url } = result.data
            uploadFile = uploadFiles[uploadFiles.length-1];
            uploadFile.name = name;
            uploadFile.url = url
        }
    }
    // 记录已经上传的图片
    fileList.value = uploadFiles
}
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'


const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
// 已上传图片数组
const fileList = ref<UploadFile[]>([])
// 引入自己封装的axios对象，用于图片的删除
import request from '@/utils/request';
import { useRoute, useRouter } from 'vue-router';
import useStudentStore from '@/store/modules/student';
const handleRemove = (file: UploadFile) => {
  request.post<any,any>('/manage/img/delete',{name:file.name}).then(response=>{
    if(response.status == 0){
        fileList.value.splice(fileList.value.indexOf(file),1)
    }
  })
}

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
};
// 获取所有已上传的图片名称
// @ts-ignore
const getImgs = ()=>{
    return fileList.value.map(item=>item.name)
}
// 获取要编辑的学生数据
const getStudent = ()=>{
  // 从路由对象中取出要编辑的学员_id
  const {_id} = $route.params
  if(_id != "-1"){
    studentStore.getStudentById(_id as string).then(response=>{
      updateStudent.value = response as studentInfoData
      const { pictures } = response as studentInfoData
      if(pictures && pictures.length != 0){
        // 类型报错
        //@ts-ignore
        fileList.value = pictures.map(item=>({
          name:item,
          url:baseApi + '/upload/' + item
        }))
      }
    })
  }
}

onMounted(()=>{
    getRoleList().then(()=>{
        getUserList().then(()=>{
            Promise.all([getClassList(),getMajorList(),getSchoolList()]).then(()=>{
              getStudent()
            })
        })
    })
})
</script>

<style scoped>
.studentBox{
    width: 70%;
    height: 100%;
    margin: 20px;
}
</style>